package com.bc.bcapi.service;

import com.bc.bccore.googleauth.GoogleAuthenticator;
import com.bc.bccore.googleauth.GoogleAuthenticatorKey;
import com.bc.bccore.googleauth.GoogleAuthenticatorQRGenerator;
import com.bc.bcmodel.domain.T_User_interface;
import com.bc.bcmodel.req.Auth2Req;
import com.bc.commoncore.security.AES;
import com.bc.commoncore.util.Digest;
import com.bc.commoncore.util.StringUtils;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.math.BigInteger;
import java.util.Map;

import com.bc.bcapi.dao.T_User_google_authMapper;
import com.bc.bcmodel.domain.T_User_google_authModel;

/**
 * @Name T_User_google_authService * @Description * @Author generation * @Date 2018/8/24 16:27:08 * @Version 1.0
 **/
@Service
public class T_User_google_authService {
    @Resource
    T_User_google_authMapper t_User_google_authMapper;

    /**
     * 保存单条数据     *      * @return
     */
    public int insert(T_User_google_authModel req) {
        return t_User_google_authMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */
    public int insertBatch(List<T_User_google_authModel> req) {
        return t_User_google_authMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    public T_User_google_authModel findByNamedParam(T_User_google_authModel req) {
        return t_User_google_authMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */
    public List<T_User_google_authModel> getAllList(T_User_google_authModel req) {
        return t_User_google_authMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */
    public PageInfo<T_User_google_authModel> getList(T_User_google_authModel req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<T_User_google_authModel> list = t_User_google_authMapper.findByNamedParamList(req);
        return new PageInfo<T_User_google_authModel>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */
    public int update(T_User_google_authModel req) {
        return t_User_google_authMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */
    public int delete(BigInteger id) {
        return t_User_google_authMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    public long count(T_User_google_authModel req) {
        return t_User_google_authMapper.count(req);
    }

    public boolean exists(String uid) {
        T_User_google_authModel t_user_google_authModel = new T_User_google_authModel();
        t_user_google_authModel.setUser_id(uid);
        t_user_google_authModel.setIsbind(1);
        t_user_google_authModel = t_User_google_authMapper.findByNamedParam(t_user_google_authModel);

        return t_user_google_authModel != null;
    }

    public JsonResult apply(String user_id,String email, String server_name) {

        T_User_google_authModel t_user_google_authModel = new T_User_google_authModel();
        t_user_google_authModel.setUser_id(user_id);
        t_user_google_authModel = t_User_google_authMapper.findByNamedParam(t_user_google_authModel);

        String secret;
        if (t_user_google_authModel != null) {
            int isBind = t_user_google_authModel.getIsbind();
            if (isBind == 1) {
                return new JsonResult(HttpReturnRnums.GOOGLE_AUTH_ACCOUNT_IS_EXIST);
            } else {
                secret = decodeSecret(t_user_google_authModel.getSecret(), user_id);
            }
        } else {
            //生成
            GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator();
            GoogleAuthenticatorKey googleAuthenticatorKey = googleAuthenticator.createCredentials();
            secret = googleAuthenticatorKey.getKey();
            String encodedSecret = encodeSecret(secret, user_id);

            //入库
            T_User_google_authModel new_t_user_google_authModel = new T_User_google_authModel();
            new_t_user_google_authModel.setUser_id(user_id);
            new_t_user_google_authModel.setIsbind(0);
            new_t_user_google_authModel.setSecret(encodedSecret);
            t_User_google_authMapper.insert(new_t_user_google_authModel);
        }

//        String email = t_user_interface.getEmail();
        String qr = GoogleAuthenticatorQRGenerator.getOtpAuthTotpURL(server_name, email, secret);

        Map<String, String> rst = new HashMap<>();
        rst.put("secret", secret);
        rst.put("qr", qr);

        return new JsonResult(rst);
    }

    public JsonResult bind(Auth2Req req, String uid) {
        if (StringUtils.isEmpty(req.getAuthtoken())) {
            return new JsonResult(HttpReturnRnums.PASSWD_IS_EMPTY);
        }

        T_User_google_authModel t_user_google_authModel = new T_User_google_authModel();
        t_user_google_authModel.setUser_id(uid);
        t_user_google_authModel = t_User_google_authMapper.findByNamedParam(t_user_google_authModel);

        if (t_user_google_authModel == null) {
            return new JsonResult(HttpReturnRnums.GOOGLE_AUTH_ACCOUNT_NOT_EXIST);
        }

        int isBind = t_user_google_authModel.getIsbind();
        if (isBind == 1) {
            return new JsonResult(HttpReturnRnums.GOOGLE_AUTH_ACCOUNT_IS_EXIST);
        }

        //验证
        String secret = decodeSecret(t_user_google_authModel.getSecret(), uid);
        GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator();
        boolean authorized = googleAuthenticator.authorize(secret, Integer.parseInt(req.getAuthtoken()));

        if (authorized) {
            //入库
            t_user_google_authModel.setIsbind(1);
            t_User_google_authMapper.update(t_user_google_authModel);
            return new JsonResult(1, "绑定成功");
        }
        return new JsonResult(0,"验证失败");
    }

    public boolean verify(String token, String uid) {
        T_User_google_authModel t_user_google_authModel = new T_User_google_authModel();
        t_user_google_authModel.setUser_id(uid);
        t_user_google_authModel.setIsbind(1);
        t_user_google_authModel = t_User_google_authMapper.findByNamedParam(t_user_google_authModel);
        String secret = decodeSecret(t_user_google_authModel.getSecret(), uid);
        GoogleAuthenticator googleAuthenticator = new GoogleAuthenticator();
        return googleAuthenticator.authorize(secret, Integer.parseInt(token));
    }

    private String encodeSecret(String secret, String str) {
        String pw = Digest.signMD5(str, Digest.ENCODE).substring(2,18);
        return AES.aesEncrypt(pw, secret);
    }

    private String decodeSecret(String secret, String str) {
        String pw = Digest.signMD5(str, Digest.ENCODE).substring(2,18);
        return AES.aesDecrypt(pw, secret);
    }

}